package testJdk.nio.testPipe;

import lombok.SneakyThrows;

import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * @author cyd
 * @version 1.0.0
 * @date 2021/11/27 16:55
 */
public class PipeDemo2 {

    public static void main(String[] args) throws Exception {
        System.out.println("start time:" + new Date());
        Pipe pipe = Pipe.open();
        new Thread(new ReadThread(pipe)).start();
        new Thread(new WriteThread(pipe, "hello cyd")).start();
    }
}

class WriteThread implements Runnable {

    private Pipe pipe;
    private String msg;

    public WriteThread(Pipe pipe, String msg) {
        this.pipe = pipe;
        this.msg = msg;
    }

    @SneakyThrows
    @Override
    public void run() {

        // 1.获取sink通道
        Pipe.SinkChannel sink = pipe.sink();
        // 2.创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        byteBuffer.put(msg.getBytes());
        byteBuffer.flip();
        // 3.写入数据，对buffer来说是读取
        // 延迟一秒
        Thread.sleep(1000);
        sink.write(byteBuffer);
        sink.close();
        System.out.println("sink close time:" + new Date());
    }
}

class ReadThread implements Runnable {

    private Pipe pipe;

    public ReadThread(Pipe pipe) {
        this.pipe = pipe;
    }

    @SneakyThrows
    @Override
    public void run() {
        // 1.获取source通道
        Pipe.SourceChannel source = pipe.source();
        // 2.创建缓冲区，读取数据
        ByteBuffer byteBuffer02 = ByteBuffer.allocate(48);

        source.read(byteBuffer02);
        byteBuffer02.flip();
        System.out.println(Charset.forName("UTF-8").decode(byteBuffer02) + "----read time:" + new Date());
        source.close();
    }
}
